﻿using KinonekoSoftware.CodariaDB.Documents.DataParts.Modules.RVE;

namespace KinonekoSoftware.Studio.Models.Modules.RVE
{
    
    public abstract class RVE_Presenter<T> : ModulePresenter where T : RVE_Element
    {
        private readonly T _AssociatedObject;

        protected virtual void OnInitialize(T _)
        {
            RaiseUpdated(nameof(Description));
            RaiseUpdated(nameof(Title));
        }

        public sealed override void DataSync(Variant variant)
        {
            
        }

        protected void RaisePropertyUpdated(string metadata)
        {
            if (string.IsNullOrEmpty(metadata))
            {
                return;
            }
            
            Queue?.OnNext(new ValueChangedMSG
            {
                Block    = TopLevel,
                Element  = this,
                Metadata = metadata,
            });
        }
        
        protected void RaiseMetadataChanged(string oldValue, string value)
        {
            if (string.IsNullOrEmpty(value))
            {
                Queue?.OnNext(new MetadataChangedMSG
                {
                    Block     = TopLevel,
                    Element   = this,
                    IsRemoved = true,
                    OldSpell  = oldValue,
                    NewSpell  = null,
                });
            }
            else
            {
                Queue?.OnNext(new MetadataChangedMSG
                {
                    Block     = TopLevel,
                    Element   = this,
                    IsRemoved = false,
                    OldSpell  = oldValue,
                    NewSpell  = value,
                });
            }
        }

        public string Id => AssociatedObject?.Id;
        

        public T AssociatedObject
        {
            get => _AssociatedObject;
            init
            {
                if (value is null)
                {
                    return;
                }
                
                _AssociatedObject = value;
                OnInitialize(value);
            }
        }

        public string Description
        {
            get => AssociatedObject?.Description;
            set
            {
                if (AssociatedObject is null)
                {
                    return;
                }

                AssociatedObject.Description = value;
                RaiseUpdated();
            }
        }

        public string Title
        {
            get => AssociatedObject?.Title ?? TextSR.Parameter_Untitled;
            set
            {
                if (AssociatedObject is null)
                {
                    return;
                }

                AssociatedObject.Title = value;
                RaiseUpdated();
            }
        }
        
        public required ModulePresenter TopLevel { get; init; }
    }
}